package com.bicon.botu.mall.goods.api;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.StringUtils;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.dto.OrderCommentParam;
import com.bicon.botu.mall.goods.entity.ProductComment;
import com.bicon.botu.mall.goods.entity.ProductCommentPraise;
import com.bicon.botu.mall.goods.service.IProductCommentPraiseService;
import com.bicon.botu.mall.goods.service.IProductCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * <p> 商品评论API-移动端
 * </p>
 *
 * @author liushujie
 * @since 2018/5/29.
 */
@RestController
@RequestMapping("/V3.0.0/api/product-comment")
public class ProductCommentApi extends BaseController {

    //SY0013-11-获取订单中未评价的商品列表—移动端  此接口在订单模块

    @Autowired
    IProductCommentService iProductCommentService;

    @Autowired
    IProductCommentPraiseService iProductCommentPraiseService;
    /**
     * SY0013-08-新增评论—移动端
     *
     * @param orderCommentParam
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public BaseResult add(@RequestParam(value = "orderCommentParam") String orderCommentParam) {
        Type type = new TypeReference<OrderCommentParam>() {
        }.getType();
        OrderCommentParam orderCommentParams =  JSONObject.parseObject(orderCommentParam,type);;
        if (StringUtils.isEmpty(orderCommentParams)) {
            return sendResult400("参数对象不能为空");
        }
        //校验参数  商户id,订单id,订单号，下单时间,商品对象
        if (StringUtils.isAnyBlank(orderCommentParams.getTenantId(), orderCommentParams.getOrderId(), orderCommentParams.getOrderNo())) {
            return sendResult400("参数不完整");
        }
        if (orderCommentParams.getProductCommentParamList().size() == 0) {
            return sendResult400("评价对象不能为空");
        }
        return iProductCommentService.insert(orderCommentParams) ? sendResult200() : sendResult500();
    }


    /**
     * SY0013-12-商品首页列表—移动端
     * 只查询3条数据
     *
     * @param productId
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public BaseResult list(@RequestParam(value = "productId") String productId, @RequestParam(value = "userId") String userId) {
        Map<String, Object> mapAll = new HashMap<>();
        //该商品前三条评论 规则：内容不能为空，按点赞数量降序排列
        Page<ProductComment> page = new ProductComment().selectPage(new Page<>(1, 3),
                new EntityWrapper<ProductComment>().where("content !=''").eq("product_id", productId).eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL).orderBy("praise_count",false).orderBy("create_date", false));
        //该商品评论总数
        int total = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        mapAll.put("total", total);
        page.setRecords(getPraise(page.getRecords(), userId));
        mapAll.put("page", page);
        return sendResult200(mapAll);
    }


    /**
     * 移动统计并搜索
     *
     * @param pageNo    当前页
     * @param pageSize  页码
     * @param productId 商品id
     * @param level     条件参数【0全部，1好评，2中评，3差评，4有图】
     * @return map
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public BaseResult search(@RequestParam(value = "pageNo") int pageNo, @RequestParam(value = "pageSize") int pageSize,
                             @RequestParam(value = "productId") String productId, @RequestParam(value = "level", defaultValue = "0") Integer level,
                             @RequestParam(value = "userId") String userId) {

        Map<String, Object> mapAll = new HashMap<>();
        //总数
        int total = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("display", GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        //好评
        int level1 = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("level", GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL1).eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        //中评
        int level2 = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("level", GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL2).eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        //差评
        int level3 = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("level", GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL3).eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        //有图总数
        int pictures = iProductCommentService.selectCount(new EntityWrapper<ProductComment>().eq("product_id", productId)
                .eq("is_pictures", 0).eq("display", 0).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        if (level.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL0)) {
            //默认查全部
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize),
                    new EntityWrapper<ProductComment>().eq("product_id", productId).eq("display", 0)
                            .eq("logic_delete", Constants.DEL_LOGIC_NORMAL)
                            .orderBy("create_date", false));
            page.setRecords(getPraise(page.getRecords(), userId));
            mapAll.put("page", page);
        } else if (level.equals(GoodsConstants.BOTU_PRODUCT_COMMENT_LEVEL4)) {
            //查有图片的
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize),
                    new EntityWrapper<ProductComment>().eq("product_id", productId).eq("display", 0).eq("is_pictures", 0)
                            .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).orderBy("create_date", false));
            page.setRecords(getPraise(page.getRecords(), userId));
            mapAll.put("page", page);
        } else {
            //根据级别查
            Page<ProductComment> page = new ProductComment().selectPage(new Page<>(pageNo, pageSize),
                    new EntityWrapper<ProductComment>().eq("product_id", productId).eq("display", 0)
                            .eq("level", level).eq("logic_delete", Constants.DEL_LOGIC_NORMAL)
                            .orderBy("create_date", false));
            page.setRecords(getPraise(page.getRecords(), userId));
            mapAll.put("page", page);
        }
        mapAll.put("total", total);
        mapAll.put("level1", level1);
        mapAll.put("level2", level2);
        mapAll.put("level3", level3);
        mapAll.put("pictures", pictures);
        return sendResult200(mapAll);
    }

    /**
     * SY0013-10-评论点赞/取消点赞—移动端
     *
     * @param id     评论ID
     * @param userId 用户ID
     * @return boolean
     */
    @RequestMapping(value = "/pictures", method = RequestMethod.POST)
    public BaseResult pictures(@RequestParam(value = "id") String id, @RequestParam(value = "userId") String userId) {
        ProductComment productComment = new ProductComment().selectById(id);
        //根据userID+commentId  查询是否有记录，
        ProductCommentPraise productCommentPraise = iProductCommentPraiseService.selectOne(new EntityWrapper<ProductCommentPraise>().eq("user_id", userId).eq("comment_id", id));
        if (!StringUtils.isEmpty(productCommentPraise)) {
            //有则删除并-1
            productComment.setPraiseCount(productComment.getPraiseCount() - 1);
            productCommentPraise.delete(new EntityWrapper<ProductCommentPraise>().eq("user_id", userId).eq("comment_id", id));
        } else {
            // 没有则 数量+1，
            productComment.setPraiseCount(productComment.getPraiseCount() + 1);
            //新增用户点赞明细
            productCommentPraise = new ProductCommentPraise();
            productCommentPraise.preInsert();
            productCommentPraise.setCommentId(id);
            productCommentPraise.setUserId(userId);
            productCommentPraise.insert();
        }
        return productComment.updateById() ? sendResult200() : sendResult500();
    }


    /**
     * 获取当前用户点过赞的评论
     *
     * @param productCommentList 评论列表
     * @param userId             当前用户id
     * @return 评论列表
     */
    private List<ProductComment> getPraise(List<ProductComment> productCommentList, String userId) {

        if(productCommentList.size()==0){
            return productCommentList;
        }
        //根据用户id 获取所有点过赞的评论
        List<ProductCommentPraise> productCommentPraise = iProductCommentPraiseService.selectList(new EntityWrapper<ProductCommentPraise>().eq("user_id", userId));
        //如果点赞明细为空，直接返回评论，没有点赞
        if (StringUtils.isEmpty(productCommentPraise)) {
            return productCommentList;
        }
        //不为空，遍历比较
        for (ProductComment productComment : productCommentList) {
            productComment.setIsPraise(0);
            for (ProductCommentPraise productCommentPraise1 : productCommentPraise) {
//                if (productCommentPraise1.getUserId().equals(productComment.getUserId())) {
                    if(productCommentPraise1.getCommentId().equals(productComment.getId())){
                        productComment.setIsPraise(1);
                        break;
                    }
//                }
            }
        }
        return productCommentList;
    }

}
